/*
 * @Author: muuzi@163.com muuzi@163.com
 * @Date: 2024-11-19 23:44:56
 * @LastEditors: muuzi@163.com muuzi@163.com
 * @LastEditTime: 2024-12-09 00:34:22
 * @FilePath: /my-vue3-project/src/hooks/web/useWxAuth.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { getWechatOpenId, login } from "@/api/login";
import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore();
export function useWxAuth() {
  const toWxLogin = () => {
    uni.showLoading({
      title: "登录中...",
      icon: "none",
    });
    uni.login({
      provider: "weixin",
      onlyAuthorize: true, // 微信登录仅请求授权认证
      success: (event) => {
        const { code } = event;
        console.log("登录授权code===", code);
        if (uni.getUserInfo) {
          uni.getUserInfo({
            provider: "weixin",
            success: async (infoRes) => {
              console.log("获取用户信息：", infoRes);
              //客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
              try {
                let res = await getWechatOpenId({
                  code,
                });
                console.log('res.data.openId',res.data.openId)
                uni.hideLoading();
                userStore.login({
                  grantType: "wechat",
                  openId: res.data.openId,
                }).then(()=>{
                 
                  uni.switchTab({
                    url:'/pages/index/index'
                  })
                });
              } catch (error) {
                uni.showToast({
                  icon: "error",
                  title: error.msg || "获取openid失败",
                });
                console.log("登录授权接口失败==s", error);
              }
            },
          });
        }
      },
      fail: (err) => {
        uni.hideLoading();
        console.log("uni.login失败", err);
        uni.showToast({
          icon: "error",
          title: err.code || "未知错误",
        });
      },
    });
  };
  return { toWxLogin };
}
